﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace T08_TaskCancel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //取消任务信号源对象
        CancellationTokenSource cts = new CancellationTokenSource();
        //手动停止事件对象
        ManualResetEvent resetEvent = new ManualResetEvent(true);

        //开启任务
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (cts.IsCancellationRequested)
                cts = new CancellationTokenSource();
            Task task = new Task(() => 
            {
                int counter = 0;
                while(!cts.IsCancellationRequested)
                {
                    resetEvent.WaitOne();//用来控制是否需要暂停和继续

                    //实际开发中，可以在这个地方编写你要实现的任务

                    counter++;
                    Thread.Sleep(300);
                    Console.WriteLine(counter);
                }
            },cts.Token);

            cts.CancelAfter(5000);//5秒后自动取消任务
            task.Start();

            //注册一个委托，当任务取消时被调用
            cts.Token.Register(() => 
            {
                Console.WriteLine("任务取消，开启清理工作...");
            });
        }

        //取消任务
        private void btnCancel_Click(object sender, EventArgs e)
        {
            cts.Cancel();
        }

        //暂停任务
        private void btnReset_Click(object sender, EventArgs e)
        {
            resetEvent.Reset();
        }
        //继续任务
        private void btnSet_Click(object sender, EventArgs e)
        {
            resetEvent.Set();
        }
    }
}